package backend.Instruction;

import backend.component.RISCVimm;
import backend.Register.RISCVoperand;

import java.util.List;

public class RISCVxor extends RISCVinst {
    private List<RISCVoperand> operands;

    public RISCVxor(List<RISCVoperand> operands) {
        this.operands = operands;
        setDst(operands.get(0));
        setSrc1(operands.get(1));
        setSrc2(operands.get(2));
    }

    private void setDst(RISCVoperand dst) {
        setDefReg(operands.get(0), dst);
        operands.set(0, dst);
    }

    private void setSrc1(RISCVoperand src) {
        addUseReg(operands.get(1), src);
        operands.set(1, src);
    }

    private void setSrc2(RISCVoperand src) {
        addUseReg(operands.get(2), src);
        operands.set(2, src);
    }


    public RISCVoperand getDst() {
        return operands.get(0);
    }

    public void replaceReg(RISCVoperand oldReg, RISCVoperand newReg) {
        if (operands.get(0).equals(oldReg)) {
            setDst(newReg);
        }
        if (operands.get(1).equals(oldReg)) {
            setSrc1(newReg);
        }
        if (operands.get(2).equals(oldReg)) {
            setSrc2(newReg);
        }
    }

    public boolean isSrc2Imm12() {
        return operands.get(2) instanceof RISCVimm && ((RISCVimm) operands.get(2)).getIs();
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("xor");
        if(isSrc2Imm12()){
            sb.append("i");
        }
        sb.append(" ").append(operands.get(0)).append(", ").append(operands.get(1)).append(", ").append(operands.get(2)).append("\n");
        return sb.toString();
    }
}
